<template>
  <div class="container">
    <el-select v-model="SelectValue" placeholder="Select" @change="handleSelectChange"  style="width: 240px;margin-left:40px;">
      <el-option
        v-for="item in options"
        :key="item.identifier"
        :label="item.title"
        :value="item.filename"
      />
    </el-select>
    <el-row :gutter="0">
      <el-col :span="12">
        <div id="leftside">
          <!-- 左侧输入区域 -->
          <div style="padding: 5px;text-align: center;">
            <el-text class="mx-1" type="primary" size="large">输入内容</el-text>
          </div>
          <div class="item">
            <Codemirror
              v-model:value="inputText"
              :options="cmOptions"
              ref="cmRef"
              height=400
              width="100%"
            ></Codemirror>
          </div>
        </div>
      </el-col>
      <el-col :span="12">
        <div id="rightSide">
          <div style="padding: 5px;text-align: center;">
            <el-text class="mx-1" type="success" size="large">处理结果</el-text>
          </div>
          <div class="item">
            <Codemirror
              v-model:value="highlightedCode"
              :options="cmOptions"
              ref="cmRef"
              height="400"
              width="100%"
            ></Codemirror>
          </div>
          <!-- 复制按钮 -->
          <div class="center" style="padding-top:10px;">
            <el-button type="info" id="copyButton" @click="copyText" plain>复制结果</el-button>
          </div>
        </div>
      </el-col>
    </el-row>
    <!-- 执行按钮 -->
    <div class="center" style="padding-top: 20px;">
      <el-button type="primary" @click="handleClick">开始执行</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { invoke } from '@tauri-apps/api/tauri';
import { ElMessage } from 'element-plus'

import useClipboard from "vue-clipboard3"

import "codemirror/mode/javascript/javascript.js";
import Codemirror from "codemirror-editor-vue3";
import type { CmComponentRef } from "codemirror-editor-vue3";
import type { EditorConfiguration } from "codemirror";


// 获取Codemirror组件实例
const cmRef = ref<CmComponentRef>();
// https://codemirror.net/5/mode/clike/index.html
// Codemirror配置
const cmOptions: EditorConfiguration = {
  mode: "text/javascript",
  lineNumbers: true,      // 显示行号
  lineWrapping: true,     // 自动换行
  indentWithTabs: true,   // 使用tab缩进
  indentUnit: 2,          // 缩进单位
};

// 输入文本
const inputText = ref<string>('');
// 高亮代码
const highlightedCode = ref<string>('');
const pyfilename = ref<string>('');

// 点击事件处理函数
const handleClick = async () => {
  console.log("开始执行",pyfilename.value,inputText.value);
  try {
    // 调用Tauri API，运行Python脚本并获取结果
    const result = await invoke<string>('run_python_script_common',{pyfilename:pyfilename.value, input: inputText.value });
    highlightedCode.value = result;
    ElMessage.success('执行完毕！')
  } catch (error) {
    console.error('Error invoking Python script:', error);
  }
};

// 功能选择
const SelectValue = ref('')
const options = ref([])

// Clipboard.js实例
  const { toClipboard } = useClipboard()
  const copyText = async () => {
      try {
        await toClipboard(highlightedCode.value);
        ElMessage.success('复制成功！')
      } catch (error) {
        ElMessage.error('复制失败.')
      }
  };

  // 处理选择项变化
  const handleSelectChange = async (value) => {
    console.log('Selected value:', value);
    // 在此处添加你的处理逻辑
    try {
      pyfilename.value=value;
      if(inputText.value.length<1){
        const result = await invoke<string>('run_python_script_example', { input: value });
        inputText.value = result;
      }
    } catch (error) {
      console.error('Error invoking Python script:', error);
    }
  };

  // 获取数据并赋值给 tableData
  const fetchData = async () => {
  try {
      const inputText = ref('some_input_text');  // 根据需要设置 inputText 的值
      // 主动调用异步函数获取数据
      const result = await invoke<string>('run_python_script_json', { input: inputText.value });
      // 假设返回的 result 是 JSON 格式的数据，解析并赋值给 tableData
      options.value = JSON.parse(result);
      // 如果 options 不为空，默认选择第一项
      if (options.value.length > 0) {
          SelectValue.value = options.value[0].title;
        }
  } catch (error) {
    console.error('Failed to fetch data:', error);
  }
  };

  // 在组件挂载时自动调用 fetchData 获取数据
  onMounted(() => {
    fetchData();
  });
</script>


<style>
.container {
  margin-top: 0px;
  width: 100%;
  display: flex;
  flex-direction: column;  /* 子元素从上往下垂直布局 */
  justify-content: flex-start; /* 子元素从顶部开始布局 */
  background-color: transparent;
}


codemirror {
  text-align: left;
  width: 100%;
  border: 1px solid #ccc;
  height: 800px;
  background-color: aquamarine;
}


#leftside,
#rightSide {
  width: 100%;
  display: flex;
  flex-direction: column; /* 子元素垂直排列 */
  justify-content: center; /* 水平方向居中 */
  background-color: transparent;
}

.item {
  text-align: left; /* 确保代码左对齐 */
}

.center {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;     /* 垂直居中（可选） */
}

</style>
